﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using TrackSystem.Entities.Dtos.Var;
using TrackSystem.UI.Server.HttpRepository.Var;

namespace TrackSystem.UI.Server.Components.Elements
{
    public partial class VarCard
    {
        [Parameter]
        public int Id { get; set; }
        /// <summary>
        /// 传感器列表数据源
        /// </summary>
        private IEnumerable<VarDto>? Regs = Enumerable.Empty<VarDto>();

        [Inject]
        public IVarHttpRepository? repo { get; set; }

        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        /// <summary>
        /// 修改状态字典，用于跟踪每个传感器的修改状态
        /// </summary>
        private ConcurrentDictionary<int, bool> changedStatus = new();

        /// <summary>
        /// 插入新数据模式
        /// </summary>
        private bool IsInsertMode { get; set; } = false;
        private VarDto? regForInsert = null;

        /// <summary>
        /// OnInitializedAsync 方法在组件初始化时调用
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            try
            {
                if (repo == null)
                {
                    await ToastService.Error("传感器列表", "数据库未初始化");
                    return;
                }

                if (Id == 0)
                    Regs = await repo.GetAll();
                else
                {
                    Regs = await repo.GetAllOfSensor(Id);
                }
                foreach (var reg in Regs)
                {
                    changedStatus.TryAdd(reg.Id, false);
                }
            }
            catch (Exception ex)
            {
                await ToastService.Error("传感器列表", ex.Message);
            }
        }

        /// <summary>
        /// OnPageClick 方法用于处理分页点击事件
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        private Task OnPageClick(int pageIndex)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// OnDeleted 方法用于处理传感器删除事件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnDeleted(int id)
        {
            if (repo == null)
            {
                await ToastService.Error("传感器列表", "数据库未初始化");
                return;
            }
            if (Regs == null || !Regs.Any())
            {
                await ToastService.Error("传感器列表", "没有可删除的传感器");
                return;
            }

            var result = await repo.DeleteVar(id);
            if (!result.Success)
            {
                await ToastService.Error("传感器删除", result.Message);
                return;
            }

            await ToastService.Success("传感器删除", "数据删除成功");
            Regs = await repo.GetAll();
            StateHasChanged();
        }

        /// <summary>
        /// OnStartInsert 方法用于开始插入新传感器数据
        /// </summary>
        /// <returns></returns>
        private async Task OnStartInsert()
        {
            IsInsertMode = true;
            regForInsert = new VarDto()
            {
                Name = "Reg1",
            };
        }

        /// <summary>
        /// OnFinishInsert 方法用于完成插入新传感器数据
        /// </summary>
        /// <returns></returns>
        private async Task OnFinishInsert()
        {
            if (repo == null)
            {
                await ToastService.Error("传感器列表", "数据库未初始化");
                return;
            }
            if (regForInsert == null)
            {
                await ToastService.Error("传感器列表", "传感器数据未准备好");
                return;
            }
            var result = await repo.DeleteVar(regForInsert.Id);
            if (!result.Success)
            {
                await ToastService.Error("传感器添加", result.Message);
                Regs = await repo.GetAll();
                StateHasChanged();
            }
            else
            {
                await ToastService.Success("传感器添加", "数据添加成功");
                IsInsertMode = false;
                regForInsert = null;
                Regs = await repo.GetAll();
                StateHasChanged();
            }
            IsInsertMode = false; // Reset insert mode
        }

        /// <summary>
        /// OnStartChange 方法用于开始修改传感器数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnStartChange(int id)
        {
            if (changedStatus.TryGetValue(id, out var status))
            {
                changedStatus[id] = true;
            }
        }

        /// <summary>
        /// OnChangedCancel 方法用于取消修改传感器数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnChangedCancel(int id)
        {
            if (changedStatus.TryGetValue(id, out var status))
            {
                changedStatus[id] = false; // Reset the status to not changed
                Regs = await repo.GetAll();
                StateHasChanged();
            }
        }

        /// <summary>
        /// OnChanged 方法用于处理传感器数据的修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnChanged(int id)
        {
            if (changedStatus.TryGetValue(id, out var status))
            {
                if (status)
                {
                    if (repo == null)
                    {
                        await ToastService.Error("传感器列表", "数据库未初始化");
                        return;
                    }

                    if (Regs == null || Regs.All(s => s.Id != id))
                    {
                        await ToastService.Error("传感器列表", "传感器不存在");
                        return;
                    }

                    var entity = Regs.FirstOrDefault(s => s.Id == id);

                    if (entity != null)
                    {
                        var result = await repo.UpdateVar(entity);
                        if (!result.Success)
                        {
                            await ToastService.Error($"传感器{entity.Name}", result.Message);
                            Regs = await repo.GetAll();
                            StateHasChanged();
                        }
                        else
                        {
                            await ToastService.Success($"传感器{entity.Name}", "数据更新成功");
                        }
                    }
                }

                changedStatus[id] = !status; // Toggle the status
            }
            else
            {
                changedStatus.TryAdd(id, false);
            }
        }
    }
}
